/**
 * @file ai_message_router.cpp
 * @brief Implementation of AI message router
 */

#include "ai_message_router.h"
#include <wx/utils.h>

AIMessageRouter& AIMessageRouter::GetInstance()
{
    static AIMessageRouter instance;
    return instance;
}

AIMessageRouter::AIMessageRouter()
{
    // 初始化消息队列
    m_messageQueues[TerminalType::HUMAN_TO_AI] = std::queue<AIMessage>();
    m_messageQueues[TerminalType::AI_TO_COMPUTER] = std::queue<AIMessage>();
    m_messageQueues[TerminalType::AI_TO_HUMAN] = std::queue<AIMessage>();
    m_messageQueues[TerminalType::COMPUTER_TO_AI] = std::queue<AIMessage>();
}

AIMessageRouter::~AIMessageRouter()
{
}

bool AIMessageRouter::Initialize()
{
    // 注册消息处理器
    RegisterMessageHandler(TerminalType::HUMAN_TO_AI, 
        [this](const AIMessage& msg) { HandleHumanToAIMessage(msg); });
    
    RegisterMessageHandler(TerminalType::AI_TO_COMPUTER,
        [this](const AIMessage& msg) { HandleAIToComputerMessage(msg); });
    
    RegisterMessageHandler(TerminalType::AI_TO_HUMAN,
        [this](const AIMessage& msg) { HandleAIToHumanMessage(msg); });
    
    RegisterMessageHandler(TerminalType::COMPUTER_TO_AI,
        [this](const AIMessage& msg) { HandleComputerToAIMessage(msg); });
    
    wxPrintf("✅ AI Message Router Initialized\n");
    return true;
}

bool AIMessageRouter::SendMessage(const AIMessage& message)
{
    if (!ValidateMessage(message)) {
        wxPrintf("❌ Invalid message: %s\n", message.ToString());
        return false;
    }
    
    wxPrintf("📨 Routing: %s\n", message.ToString());
    
    RouteMessage(message);
    return true;
}

bool AIMessageRouter::ReceiveMessage(AIMessage& message, TerminalType receiver)
{
    if (m_messageQueues[receiver].empty()) {
        return false;
    }
    
    message = m_messageQueues[receiver].front();
    m_messageQueues[receiver].pop();
    
    return true;
}

void AIMessageRouter::RouteMessage(const AIMessage& message)
{
    // 根据目的地路由消息
    switch (message.destination) {
        case TerminalType::AI_TO_COMPUTER:
            m_messageQueues[TerminalType::AI_TO_COMPUTER].push(message);
            if (m_messageHandlers.count(TerminalType::AI_TO_COMPUTER)) {
                m_messageHandlers[TerminalType::AI_TO_COMPUTER](message);
            }
            break;
            
        case TerminalType::AI_TO_HUMAN:
            m_messageQueues[TerminalType::AI_TO_HUMAN].push(message);
            if (m_messageHandlers.count(TerminalType::AI_TO_HUMAN)) {
                m_messageHandlers[TerminalType::AI_TO_HUMAN](message);
            }
            break;
            
        case TerminalType::HUMAN_TO_AI:
            m_messageQueues[TerminalType::HUMAN_TO_AI].push(message);
            if (m_messageHandlers.count(TerminalType::HUMAN_TO_AI)) {
                m_messageHandlers[TerminalType::HUMAN_TO_AI](message);
            }
            break;
            
        case TerminalType::COMPUTER_TO_AI:
            m_messageQueues[TerminalType::COMPUTER_TO_AI].push(message);
            if (m_messageHandlers.count(TerminalType::COMPUTER_TO_AI)) {
                m_messageHandlers[TerminalType::COMPUTER_TO_AI](message);
            }
            break;
    }
}

void AIMessageRouter::RegisterMessageHandler(TerminalType terminal, std::function<void(const AIMessage&)> handler)
{
    m_messageHandlers[terminal] = handler;
}

wxString AIMessageRouter::GetSystemStatus() const
{
    wxString status = "AI Message Router Status:\n";
    
    for (const auto& queue : m_messageQueues) {
        status += wxString::Format("  %s: %zu messages\n",
            AIMessage::TerminalToString(queue.first), queue.second.size());
    }
    
    status += wxString::Format("  Registered handlers: %zu\n", m_messageHandlers.size());
    
    return status;
}

void AIMessageRouter::HandleHumanToAIMessage(const AIMessage& message)
{
    wxPrintf("🤖 Processing human command: %s\n", message.content);
    
    // 这里可以连接到真正的AI处理
    // 现在模拟AI处理
    AIMessage aiResponse;
    aiResponse.msgType = MessageType::COMMAND_TO_COMPUTER;
    aiResponse.source = TerminalType::AI_TO_COMPUTER;
    aiResponse.destination = TerminalType::COMPUTER_TO_AI;
    aiResponse.content = "Processed: " + message.content;
    aiResponse.messageId = message.messageId + "_ai_processed";
    
    SendMessage(aiResponse);
}

void AIMessageRouter::HandleAIToComputerMessage(const AIMessage& message)
{
    wxPrintf("🖥️  AI command to computer: %s\n", message.content);
    
    // 执行计算机命令
    AIMessage computerResponse = m_aiComputerTerminal.ExecuteAICommand(message);
    computerResponse.destination = TerminalType::AI_TO_HUMAN;
    
    SendMessage(computerResponse);
}

void AIMessageRouter::HandleAIToHumanMessage(const AIMessage& message)
{
    wxPrintf("👤 AI response to human: %s\n", message.content);
    
    // 显示给人类
    m_humanAITerminal.DisplayAIResponse(message);
}

void AIMessageRouter::HandleComputerToAIMessage(const AIMessage& message)
{
    wxPrintf("🖥️→🤖 Computer response to AI: %s\n", message.content);
    
    // 转发给AI（这里可以进一步处理）
    AIMessage forwardMessage = message;
    forwardMessage.destination = TerminalType::AI_TO_HUMAN;
    
    SendMessage(forwardMessage);
}

bool AIMessageRouter::ValidateMessage(const AIMessage& message)
{
    if (message.content.IsEmpty()) {
        return false;
    }
    
    if (message.source == message.destination) {
        return false; // 不能发送给自己
    }
    
    return true;
}
